<template>
  <div class="dashboard-container">
    <!-- 顶部数据概览 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon" style="background-color: #5b8ff9">
              <i class="el-icon-user"></i>
            </div>
            <div class="card-info">
              <div class="card-title">学员总数</div>
              <div class="card-number">{{ statistics.studentCount }}</div>
              <div class="card-trend" :class="{ 'positive': studentGrowth >= 0 }">
                <i :class="studentGrowth >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(studentGrowth) }}% 同比
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon" style="background-color: #5ad8a6">
              <i class="el-icon-s-custom"></i>
            </div>
            <div class="card-info">
              <div class="card-title">教练总数</div>
              <div class="card-number">{{ statistics.coachCount }}</div>
              <div class="card-trend" :class="{ 'positive': coachGrowth >= 0 }">
                <i :class="coachGrowth >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(coachGrowth) }}% 同比
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon" style="background-color: #5e7ce0">
              <i class="el-icon-document"></i>
            </div>
            <div class="card-info">
              <div class="card-title">本月预约</div>
              <div class="card-number">{{ statistics.appointmentCount }}</div>
              <div class="card-trend" :class="{ 'positive': appointmentGrowth >= 0 }">
                <i :class="appointmentGrowth >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(appointmentGrowth) }}% 同比
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon" style="background-color: #f6bd16">
              <i class="el-icon-s-flag"></i>
            </div>
            <div class="card-info">
              <div class="card-title">通过率</div>
              <div class="card-number">{{ statistics.passRate }}%</div>
              <div class="card-trend" :class="{ 'positive': passRateGrowth >= 0 }">
                <i :class="passRateGrowth >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                {{ Math.abs(passRateGrowth) }}% 同比
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

 <!-- 图表区域 -->
<el-row :gutter="20" class="chart-section">
  <!-- 左侧图表 -->
  <el-col :span="14"> <!-- ✅ 从 16 改为 14 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>月度学员增长趋势</span>
        </div>
      </template>
      <div class="chart-container">
        <v-chart ref="studentChart" :option="studentChartOption" autoresize />
      </div>
    </el-card>
  </el-col>

  <!-- 右侧图表 -->
  <el-col :span="10"> <!-- ✅ 从 8 改为 10 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>教练技能分布</span>
        </div>
      </template>
      <div class="chart-container">
        <v-chart ref="specializationChart" :option="specializationChartOption" autoresize />
      </div>
    </el-card>
  </el-col>
</el-row>


    <el-row :gutter="20" class="chart-section">
      <!-- 左侧图表 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>预约状态分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="appointmentChart" :option="appointmentChartOption" autoresize />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧图表 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>教练工作年限分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="experienceChart" :option="experienceChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增图表行 -->
    <el-row :gutter="20" class="chart-section">
      <!-- 学员性别分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>学员性别分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="genderChart" :option="genderChartOption" autoresize />
          </div>
        </el-card>
      </el-col>

      <!-- 学员驾照类型分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>学员驾照类型分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="licenseTypeChart" :option="licenseTypeChartOption" autoresize />
          </div>
        </el-card>
      </el-col>

      <!-- 教练评分分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>教练评分分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="coachRatingChart" :option="coachRatingChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-section">
      <!-- 学员学习进度分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>学员学习进度分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="progressChart" :option="progressChartOption" autoresize />
          </div>
        </el-card>
      </el-col>

      <!-- 教练活跃状态 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>教练活跃状态</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="coachActiveChart" :option="coachActiveChartOption" autoresize />
          </div>
        </el-card>
      </el-col>

      <!-- 训练项目活跃状态 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>训练项目活跃状态</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="programActiveChart" :option="programActiveChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-section">
      <!-- 学员训练状态分布 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>学员训练状态分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart ref="trainingStatusChart" :option="trainingStatusChartOption" autoresize />
          </div>
        </el-card>
      </el-col>

      <!-- 空白区域 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>数据统计概览</span>
            </div>
          </template>
          <div class="chart-container" style="display: flex; align-items: center; justify-content: center;">
            <div class="placeholder-text">
              <i class="el-icon-data-analysis" style="font-size: 48px; color: #c0c4cc;"></i>
              <p style="margin-top: 15px; color: #909399;">更多数据统计图表</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部数据表格 -->
    <el-row :gutter="20" class="table-section">
      <el-col :span="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>最新学员</span>
            </div>
          </template>
          <el-table :data="recentStudents" style="width: 100%" max-height="300">
            <el-table-column prop="fullname" label="姓名" />
            <el-table-column prop="enrollment_date" label="报名日期" />
            <el-table-column prop="status" label="状态" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>最新预约</span>
            </div>
          </template>
          <el-table :data="recentAppointments" style="width: 100%" max-height="300">
            <el-table-column prop="student_name" label="学员" />
            <el-table-column prop="coach_name" label="教练" />
            <el-table-column prop="appointment_date" label="预约日期" />
            <el-table-column prop="status" label="状态" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import requestUtil from '@/util/request.js'
import { ElMessage } from 'element-plus'

// 注册 echarts 组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 数据相关
const statistics = ref({
  studentCount: 0,
  coachCount: 0,
  appointmentCount: 0,
  passRate: 0
})

const studentGrowth = ref(0)
const coachGrowth = ref(0)
const appointmentGrowth = ref(0)
const passRateGrowth = ref(0)

const recentStudents = ref([])
const recentAppointments = ref([])

// 图表配置
const studentChartOption = ref({
  title: {
    text: '学员增长趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    data: [],
    type: 'line',
    smooth: true,
    itemStyle: { color: '#5b8ff9' }
  }]
})

const specializationChartOption = ref({
  title: {
    text: '教练技能分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: '20%',
    textStyle: {
      fontSize: 12,
      color: '#666'
    },
    itemWidth: 14,        // 颜色块宽度
    itemHeight: 14,       // 颜色块高度
    itemGap: 15,          // 项目间距
    formatter: function(name) {
      return name;         // 显示原始名称，避免截断
    }
  },
  series: [{
    type: 'pie',
    radius: ['60%', '80%'],
    data: [],
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    },
    label: {
  show: false // 关闭所有标签
},
    labelLine: {
      show: false,
    },
    avoidLabelOverlap: true,
    minAngle: 5,
    itemStyle: {
      borderRadius: 5
    }
  }]
})

const appointmentChartOption = ref({
  title: {
    text: '预约状态分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: 'bottom'
  },
  series: [{
    type: 'pie',
    radius: ['40%', '70%'],
    data: [],
    avoidLabelOverlap: false,
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: '14',
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    }
  }]
})

const experienceChartOption = ref({
  title: {
    text: '教练工作年限分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    data: [],
    type: 'bar',
    itemStyle: {color: '#f6bd16'}
  }]
})

// 新增图表配置
const genderChartOption = ref({
  title: {
    text: '学员性别分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: 'bottom'
  },
  series: [{
    type: 'pie',
    radius: ['40%', '70%'],
    data: [],
    avoidLabelOverlap: false,
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: '14',
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    }
  }]
})

const licenseTypeChartOption = ref({
  title: {
    text: '学员驾照类型分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: 'bottom'
  },
  series: [{
    type: 'pie',
    radius: '70%',
    data: [],
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }]
})

const coachRatingChartOption = ref({
  title: {
    text: '教练评分分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['1分', '2分', '3分', '4分', '5分']
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    data: [0, 0, 0, 0, 0],
    type: 'bar',
    itemStyle: {color: '#5b8ff9'}
  }]
})

const progressChartOption = ref({
  title: {
    text: '学员学习进度分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['0-20%', '20-40%', '40-60%', '60-80%', '80-100%']
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    data: [0, 0, 0, 0, 0],
    type: 'bar',
    itemStyle: {color: '#5ad8a6'}
  }]
})

const coachActiveChartOption = ref({
  title: {
    text: '教练活跃状态',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: 'bottom'
  },
  series: [{
    type: 'pie',
    radius: ['40%', '70%'],
    data: [],
    avoidLabelOverlap: false,
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: '14',
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    }
  }]
})

const programActiveChartOption = ref({
  title: {
    text: '训练项目活跃状态',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: 'bottom'
  },
  series: [{
    type: 'pie',
    radius: ['40%', '70%'],
    data: [],
    avoidLabelOverlap: false,
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: '14',
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    }
  }]
})

const trainingStatusChartOption = ref({
  title: {
    text: '学员训练状态分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    bottom: 'bottom'
  },
  series: [{
    type: 'pie',
    radius: '70%',
    data: [],
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }]
})

// 数据获取函数
const fetchStatistics = async () => {
  try {
    // 获取统计数据
    const statsRes = await requestUtil.get('/dashboard/stats')
    statistics.value = statsRes.data.data

    // 获取增长数据
    const growthRes = await requestUtil.get('/dashboard/growth')
    const growthData = growthRes.data.data
    studentGrowth.value = growthData.studentGrowth
    coachGrowth.value = growthData.coachGrowth
    appointmentGrowth.value = growthData.appointmentGrowth
    passRateGrowth.value = growthData.passRateGrowth
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

const fetchStudentTrend = async () => {
  try {
    const res = await requestUtil.get('/dashboard/student-trend')
    const data = res.data.data

    studentChartOption.value.xAxis.data = data.months
    studentChartOption.value.series[0].data = data.studentCounts
  } catch (error) {
    ElMessage.error('获取学员趋势数据失败')
  }
}

const fetchSpecializationData = async () => {
  try {
    const res = await requestUtil.get('/dashboard/coach-specialization')
    const data = res.data.data

    specializationChartOption.value.series[0].data = data.map(item => ({
      value: item.count,
      name: item.specialization
    }))
  } catch (error) {
    ElMessage.error('获取教练技能数据失败')
  }
}

const fetchAppointmentStatus = async () => {
  try {
    const res = await requestUtil.get('/dashboard/appointment-status')
    const data = res.data.data

    appointmentChartOption.value.series[0].data = [
      {value: data.pending, name: '待确认'},
      {value: data.confirmed, name: '已确认'},
      {value: data.cancelled, name: '已取消'}
    ]
  } catch (error) {
    ElMessage.error('获取预约状态数据失败')
  }
}

// 修改后的教练工作年限分布数据获取函数
const fetchExperienceData = async () => {
  try {
    // 获取所有教练数据（获取全部数据）
    let allCoaches = [];
    let page = 1;
    let hasMore = true;

    // 循环获取所有页面的教练数据
    while (hasMore) {
      const res = await requestUtil.get('/coach/msg', {
        page: page,
        page_size: 100 // 每次获取100条数据
      });

      const coaches = res.data.data;
      allCoaches = [...allCoaches, ...coaches];

      // 检查是否还有更多数据
      if (coaches.length < 100) {
        hasMore = false;
      } else {
        page++;
      }
    }

    // 统计不同工作年限的教练数量
    const experienceMap = {};

    allCoaches.forEach(coach => {
      const years = coach.years_of_experience || 0;
      experienceMap[years] = (experienceMap[years] || 0) + 1;
    });

    // 转换为图表需要的格式
    const years = Object.keys(experienceMap).sort((a, b) => a - b);
    const counts = years.map(year => experienceMap[year]);

    experienceChartOption.value.xAxis.data = years.map(year => `${year}年`);
    experienceChartOption.value.series[0].data = counts;
  } catch (error) {
    ElMessage.error('获取教练经验数据失败');
  }
};

// 新增数据获取函数
const fetchGenderData = async () => {
  try {
    const res = await requestUtil.get('/dashboard/student-gender')
    const data = res.data.data

    genderChartOption.value.series[0].data = [
      {value: data.male, name: '男'},
      {value: data.female, name: '女'},
      {value: data.other, name: '其他'}
    ]
  } catch (error) {
    ElMessage.error('获取学员性别数据失败')
  }
}

const fetchLicenseTypeData = async () => {
  try {
    const res = await requestUtil.get('/dashboard/student-license-type')
    const data = res.data.data

    licenseTypeChartOption.value.series[0].data = data.map(item => ({
      value: item.count,
      name: item.license_type
    }))
  } catch (error) {
    ElMessage.error('获取学员驾照类型数据失败')
  }
}

const fetchCoachRatingData = async () => {
  try {
    const res = await requestUtil.get('/dashboard/coach-rating')
    const data = res.data.data

    coachRatingChartOption.value.series[0].data = [
      data.one,
      data.two,
      data.three,
      data.four,
      data.five
    ]
  } catch (error) {
    ElMessage.error('获取教练评分数据失败')
  }
}

const fetchProgressData = async () => {
  try {
    const res = await requestUtil.get('/dashboard/student-progress')
    const data = res.data.data

    progressChartOption.value.series[0].data = [
      data.range1,
      data.range2,
      data.range3,
      data.range4,
      data.range5
    ]
  } catch (error) {
    ElMessage.error('获取学员进度数据失败')
  }
}

const fetchCoachActiveData = async () => {
  try {
    const res = await requestUtil.get('/dashboard/coach-active')
    const data = res.data.data

    coachActiveChartOption.value.series[0].data = [
      {value: data.active, name: '在职'},
      {value: data.inactive, name: '离职'}
    ]
  } catch (error) {
    ElMessage.error('获取教练活跃状态数据失败')
  }
}

const fetchProgramActiveData = async () => {
  try {
    const res = await requestUtil.get('/dashboard/program-active')
    const data = res.data.data

    programActiveChartOption.value.series[0].data = [
      {value: data.active, name: '激活'},
      {value: data.inactive, name: '未激活'}
    ]
  } catch (error) {
    ElMessage.error('获取训练项目活跃状态数据失败')
  }
}

const fetchTrainingStatusData = async () => {
  try {
    const res = await requestUtil.get('/dashboard/training-status')
    const data = res.data.data

    trainingStatusChartOption.value.series[0].data = [
      {value: data.scheduled, name: '已安排'},
      {value: data.completed, name: '已完成'},
      {value: data.completed, name: '未通过'},
    ]
  } catch (error) {
    ElMessage.error('获取训练状态数据失败')
  }
}

const fetchRecentData = async () => {
  try {
    // 获取最新学员
    const studentsRes = await requestUtil.get('/dashboard/recent-students')
    recentStudents.value = studentsRes.data.data

    // 获取最新预约
    const appointmentsRes = await requestUtil.get('/dashboard/recent-appointments')
    recentAppointments.value = appointmentsRes.data.data.map(item => ({
      ...item,
      status: mapStatusToChinese(item.status)
    }))
  } catch (error) {
    ElMessage.error('获取最新数据失败')
  }
}

// 状态映射函数
const mapStatusToChinese = (status) => {
  const map = {
    PENDING: '待确认',
    CONFIRMED: '已确认',
    CANCELLED: '已取消'
  }
  return map[status] || status
}


// 初始化数据
const initDashboard = async () => {
  await Promise.all([
    fetchStatistics(),
    fetchStudentTrend(),
    fetchSpecializationData(),
    fetchAppointmentStatus(),
    fetchExperienceData(),
    fetchGenderData(),
    fetchLicenseTypeData(),
    fetchCoachRatingData(),
    fetchProgressData(),
    fetchCoachActiveData(),
    fetchProgramActiveData(),
    fetchTrainingStatusData(),
    fetchRecentData()
  ])
}

// 生命周期
onMounted(() => {
  initDashboard()
})
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.data-overview {
  margin-bottom: 20px;
}

.overview-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .card-content {
    display: flex;
    align-items: center;

    .card-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;

      i {
        font-size: 24px;
        color: white;
      }
    }

    .card-info {
      flex: 1;

      .card-title {
        font-size: 14px;
        color: #606266;
        margin-bottom: 5px;
      }

      .card-number {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 5px;
      }

      .card-trend {
        font-size: 12px;
        color: #f56c6c;

        &.positive {
          color: #67c23a;
        }

        i {
          margin-right: 3px;
        }
      }
    }
  }
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card, .table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .card-header {
    font-weight: bold;
    color: #303133;
  }

  .chart-container {
    height: 300px;
  }
}

.table-section {
  .el-table {
    margin-top: 10px;
  }
}

.placeholder-text {
  text-align: center;
  color: #909399;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

</style>
